package com.yezao.yzrouter

import android.content.Context
import android.net.Uri
import com.yezao.yzrouter.schemaparser.AbsSchemaParser
import com.yezao.yzrouter.touterParser.IRouterParser
import com.yezao.yzrouter.touterParser.JsonParser
import com.yezao.yzrouter.touterParser.RouterXmlParser
import org.json.JSONArray
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException

object YZRouter :IRouter{
    const val TAG = "YZRouter"


    private val schemaParsers = ArrayList<AbsSchemaParser>()
    override fun init(context: Context) {
        defaultLoadFromAnnotation(context)
    }


    override fun registSchemaParsers(vararg parser: AbsSchemaParser) {
        schemaParsers.addAll(parser)
    }

    override fun  registRoutes(collection: Map<String, String>) {

       RouterTable.registRoutes(collection)
    }

    override fun unregistRoutes(collection: Map<String,Class<*>>) {
        TODO("Not yet implemented")
    }

    override fun loadFromJson(context: Context,jsonRes: Int) {
        val parser:IRouterParser = JsonParser()
        val map = parser.parseFromRes(context, jsonRes)
        registRoutes(map)
    }

    override fun loadFromXml(context: Context,xml: Int) {
        val parser:IRouterParser = RouterXmlParser()
        val map = parser.parseFromRes(context, xml)
        registRoutes(map)
    }

    fun defaultLoadFromAnnotation(context: Context){
        val jsonParser = JsonParser()
        try {
            val open = context.assets.open("yz-route-map.json")
            val parseFromIO = jsonParser.parseFromIO(context, open)
            registRoutes(parseFromIO)
        } catch (e: Exception) {
        }
    }

    /**
     * 找到与 schema 对应的 解析器
     *
     * */
    override fun findSchemaParser(schema: String): AbsSchemaParser {
        for (schemaParser in schemaParsers) {
            if (schemaParser.checkSchema(schema)) {
                return schemaParser
            }
        }
        throw IllegalArgumentException("没有找到对应的 SchemaParser解析器 请确认是否注册了正确的解析器并检查路由 "+schema)
    }

    /**
     * 最常用的 跳转方法  url 中包含了参数 需要对这个 url 进行解析
     *
     * */
    override fun goTo(from:Context,routeUrl: String) {
        val uri = Uri.parse(routeUrl)
        println(uri.scheme)
        uri.scheme?.run {
            val parser = findSchemaParser(this)
            val paramsBundle = parser.createBundle(uri)
            if (paramsBundle.containsKey("page")) {
                val fragmentRoute = parser.getFragmentRoute(uri)?:throw IllegalAccessException("fragment route not found")

                val fragmentClassName = RouterTable.getLocalClass(fragmentRoute)?:throw IllegalAccessException("fragment class not found")//这个是路由里面定义的fragmentclass 名称
                paramsBundle.putString("page",fragmentClassName)
            }
            val route = parser.getRoute(uri)?:throw IllegalArgumentException("route is null ")
            //这个localclass 定位到activity级别 fragment 通过bundle 传递
            val localClass = RouterTable.getLocalClass(route)?:throw IllegalStateException("target class not found")
            val parseIntent = parser.parseIntent(from,localClass,paramsBundle)?:throw IllegalStateException("无法识别的 类型")
            from.startActivity(parseIntent)
        }?:throw IllegalAccessException("schema unfind error")
    }

}